<?php

namespace app\v1\logic;

use app\services\DyService\DyLogin;
use app\v1\model\MiniUser;
use think\Db;

class MiniUserLogic
{
    public MiniUser $model;

    public function __construct()
    {
        $this->model = new MiniUser();
    }

    public function login($param): array
    {
        if (empty($param['code'])) return [false, '参数错误'];

        $loginService = new DyLogin($param['code']);

        $result = $loginService->code2Session();
        if ($result['err_no'] !== 0) {
            return [false, $result['err_tips']];
        }
        $openid = $result['data']['openid'] ?? '';
        if (!$openid) return [false, '获取openid失败'];

        Db::startTrans();
        try {
            $has = $this->model->where('openid', $openid)->find();
            $recordData = [
                'create_time' => time()
            ];
            $prefixId = 0;
            if (!$has) {
                $insertRes = $this->model->create(['openid' => $openid, 'last_login' => time()]);
                $prefixId = $insertRes->user_id;
                // 日志
                $recordData['user_id'] = $prefixId;
                $recordData['type'] = 2;
            } else {
                $has->save(['last_login' => time()]);
                $prefixId = $has->user_id;
                // 日志
                $recordData['user_id'] = $prefixId;
                $recordData['type'] = 1;
            }
            Db::name('mini_user_record')->insert($recordData);
            $userInfo = $this->getUserInfo($prefixId);
            Db::commit();
            return [true, ['token' => think_ucenter_encrypt($prefixId, 'zsx-admin', 60 * 60 * 24 * 7), 'userInfo' => $userInfo]];
        } catch (\Throwable $t) {
            Db::rollback();
            return [false, [$t->getFile(), $t->getLine(), $t->getMessage()]];
        }
    }

    public function saveInfo($param, $userId): array
    {
        if (!$userId) return [false, '参数错误'];
        Db::startTrans();
        try {
            $info = $this->model->find($userId);
            $info->save($param);
            $userInfo = $this->getUserInfo($userId);
            Db::commit();
            return [true, $userInfo];
        } catch (\Throwable $t) {
            Db::rollback();
            return [false, [$t->getFile(), $t->getLine(), $t->getMessage()]];
        }
    }

    public function getUserInfo($id): array
    {
        $info = $this->model->find($id)->toArray();
        unset($info['openid']);
        return $info;
    }
}